
require 'cgi'

module Oos4ruby
class Search
  
=begin rdoc
  Method to search services/places into 11870. Returns a Sites collection
  available parameters:
  <tt>q</tt>:: string that represents a siple query.
  <tt>bbox</tt>:: array of points that delimiters a rectangle, SW and NE.
  <tt>as</tt>:: area specified by a slug. I.E: /es/madrid.
  <tt>tags</tt>:: array of tags.
  <tt>tag_op</tt>:: tags operator, "and" or "or".
  <tt>lat</tt>:: latitude of the center point of an area.
  <tt>lon</tt>:: longitude of the center point of an area.
  <tt>radius</tt>:: radius to create a rectangle from the center point of an area.
  <tt>page</tt>:: page number in the search results
=end
  def Search.find(auth, opts)
    query = SEARCH_URL
    
    more_params = false
    unless opts.empty?
      query += "?"
      if opts[:q]
        query += "q=#{CGI.escape(opts[:q])}"
        more_params = true
      end
      if opts[:bbox]
        query += "&" if more_params
        query += "bbox=#{opts[:bbox].join(",")}"
        more_params = true
      end
      if opts[:as]
        query += "&" if more_params
        query += "as=#{opts[:as]}"
        more_params = true
      end
      if opts[:tags]
        query += "&" if more_params
        opts[:tags].each_with_index do |tag, index|
          query += "tag=#{CGI.escape(tag)}"          
          query += "&" if index < opts[:tags].length - 1
        end
        more_params = true
      end
      if opts[:tag_op]
        query += "&" if more_params
        query += "tagOp=#{opts[:tag_op]}"
        more_params = true
      end
      if opts[:lat] and opts[:lon] and opts[:radius]
        query += "&" if more_params
        query += "lat=#{opts[:lat]}&lon=#{opts[:lon]}&radius=#{opts[:radius]}"
        more_params = true
      end
      if opts[:page]
        query += "&" if more_params
        query += "page=#{opts[:page]}"
      end
    else
      raise RuntimeError('a parameter is obligatory at least')
    end
    
    getter = HTTPInvoker.new query, auth
    
    worked = getter.get
    raise RuntimeError.new(getter.response.message) unless worked
    Sites.new(Feed.read(getter.body), auth, nil)
  end
end
end


